package com.example.demo.his.leetcode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @auther zzc
 * @date 2021/3/31 17:01
 */
public class 二叉树的层数遍历 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    /**
     * 广度优先遍历
     * 使用广度优先搜索
     * 使用到队列   存每层的临时节点
     */
    public List<List<TreeNode>> bft(TreeNode root) {
        if (root == null) {
            return null;
        }
        //存结果
        List<List<TreeNode>> res = new ArrayList<>();
        //需要一直遍历
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (queue.size() > 0) {
            int size = queue.size();
            //存放每层的临时节点    添加到结果list中
            List<TreeNode> tmp = new ArrayList<>();
            //如果左右节点不为空  则都放进队列中
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.remove();
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
                tmp.add(node);
            }
            res.add(tmp);
        }
        return res;
    }


}
